<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>薪酬管理 - 薪酬概览</title>
    <link rel="stylesheet" href="../../css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="../../js/components/navigation.js"></script>
    <script src="../../js/utils.js"></script>
    <script src="../../js/api.js"></script>
    <style>
        .stats-cards{
            display: flex;
            justify-content: space-around;
            gap: px;
        }
        .stats-cards .card{
            width: 100%;
        }
        .filter-group{
            display: flex;
            gap: 20px;
            justify-content: space-around;
        }
        .part{
            /*display: flex;*/
        }
        /*.filter-group .input-group{
            height: 40px;
            width: 100%;
        }*/
        
        /* 薪酬表格样式 */
        .salary-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .salary-table thead {
            background-color: #2c3e50;
            color: white;
        }
        .salary-table th,
        .salary-table td {
            padding: 12px 15px;
            text-align: left;
        }
        .salary-table tbody tr {
            transition: background-color 0.3s ease;
            border-bottom: 1px solid #f1f1f1;
        }
        .salary-table tbody tr:hover {
            background-color: #f8f9fa;
        }
        .salary-table tbody tr:last-child {
            border-bottom: none;
        }
        .salary-table .total-column {
            font-weight: bold;
            color: #2c3e50;
        }
        .salary-table .btn-sm {
            padding: 6px 10px;
            border-radius: 4px;
        }
        .salary-table .no-data {
            color: #7f8c8d;
            padding: 40px 0;
        }
    </style>
</head>
<body>
    <div class="loading-overlay" id="loading-overlay">
        <div class="loading-spinner"></div>
    </div>

    <div class="toast" id="toast"></div>

    <div class="app-container">
        <header class="app-header">
            <div class="logo">
                <i class="fas fa-building"></i> 员工管理系统
            </div>
            <div class="user-info">
                <span id="username-display" class="username"></span>
                <button id="logout-btn" class="btn btn-secondary">
                    <i class="fas fa-sign-out-alt"></i> 退出登录
                </button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">欢迎页</a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">员工管理</a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">员工列表</a></li>
                                <li><a href="../employee/add.html" class="submenu-item">添加员工</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">业务管理</a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">业务列表</a></li>
                                <li><a href="../business/create.html" class="submenu-item">创建业务</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">薪酬管理</a>
                            <ul class="submenu">
                                <li><a href="../salary/overview.html" class="submenu-item">薪酬概览</a></li>
                                <li><a href="../salary/manage.html" class="submenu-item">薪酬管理</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">系统设置</a>
                            <ul class="submenu">
                                <li><a href="../system/user.html" class="submenu-item">用户管理</a></li>
                                <li><a href="../system/profile.html" class="submenu-item">个人设置</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="page-header">
                    <h1><i class="fas fa-money-bill-wave"></i> 薪酬概览</h1>
                    <div class="breadcrumb">
                        <a href="#"><i class="fas fa-home"></i> 首页</a> &gt;
                        <a href="#"><i class="fas fa-money-bill-wave"></i> 薪酬管理</a> &gt;
                        <span><i class="fas fa-chart-line"></i> 薪酬概览</span>
                    </div>
                </div>


                <div class="stats-cards mt-4">
                    <div class="card stat-card">
                        <div class="card-body">
                            <div class="card-title"><i class="fas fa-wallet"></i> 总薪酬支出</div>
                            <div class="card-value" id="total-salary">¥0.00</div>
                            <div class="card-change positive"><i class="fas fa-arrow-up"></i> +5.2% 较上月</div>
                        </div>
                    </div>
                    <div class="card stat-card">
                        <div class="card-body">
                            <div class="card-title"><i class="fas fa-users"></i> 平均薪资</div>
                            <div class="card-value" id="avg-salary">¥0.00</div>
                            <div class="card-change positive"><i class="fas fa-arrow-up"></i> +2.8% 较上月</div>
                        </div>
                    </div>
                    <div class="card stat-card">
                        <div class="card-body">
                            <div class="card-title"><i class="fas fa-chart-line"></i> 薪酬增长率</div>
                            <div class="card-value" id="salary-growth">0%</div>
                            <div class="card-change negative"><i class="fas fa-arrow-down"></i> -0.5% 较上月</div>
                        </div>
                    </div>
                    <div class="card stat-card">
                        <div class="card-body">
                            <div class="card-title"><i class="fas fa-gift"></i> 福利支出</div>
                            <div class="card-value" id="benefit-expense">¥0.00</div>
                            <div class="card-change positive"><i class="fas fa-arrow-up"></i> +3.1% 较上月</div>
                        </div>
                    </div>
                </div>


                <div class="card">
                    <div class="card-header">
                        <h2>筛选条件</h2>
                    </div>
                    <div class="card-body">
                        <div class="filter-group col-md-3">
                            <div class="part">
                                <label for="date-range" class="form-label">日期范围</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                    </div>
                                    <select id="date-range" class="form-control">
                                        <option value="month" selected>本月</option>
                                        <option value="quarter">本季度</option>
                                        <option value="year">本年</option>
                                        <option value="custom">自定义</option>
                                    </select>
                                </div>
                            </div>
                            <div class="part">
                                <label for="start-date" class="form-label">开始日期</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-calendar-day"></i></span>
                                    </div>
                                    <input type="date" id="start-date" class="form-control">
                                </div>
                            </div>
                            <div class="part">
                                <label for="end-date" class="form-label">结束日期</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-calendar-day"></i></span>
                                    </div>
                                    <input type="date" id="end-date" class="form-control">
                                </div>
                            </div>
                            <div class="part">
                                <label for="department-filter" class="form-label">部门</label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><i class="fas fa-building"></i></span>
                                    </div>
                                    <select id="department-filter" class="form-control">
                                        <option value="all">全部部门</option>
                                        <option value="技术部">技术部</option>
                                        <option value="市场部">市场部</option>
                                        <option value="财务部">财务部</option>
                                        <option value="人力资源部">人力资源部</option>
                                    </select>
                                </div>
                            </div>
                            <div class="part">
                                <div class="form-label">
                                    &nbsp;
                                </div>
                                <div>
                                    <button id="apply-filter" class="btn btn-primary">
                                        <i class="fas fa-filter"></i> 应用筛选
                                    </button>
                                    <button id="export-report" class="btn btn-secondary ml-2">
                                        <i class="fas fa-download"></i> 导出报表
                                    </button>
                                </div>

                            </div>

                        </div>

                    </div>
                </div>





                <div class="card mt-4">
                    <div class="card-header">
                        <h3><i class="fas fa-list"></i> 薪酬明细</h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="data-table table-hover table-striped salary-table">
                                <thead>
                                    <tr>
                                        <th>员工姓名</th>
                                        <th>部门</th>
                                        <th>职位</th>
                                        <th>基本工资</th>
                                        <th>奖金</th>
                                        <th>福利</th>
                                        <th>总计</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="salary-table-body">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                        <div class="pagination mt-3">
                            <button class="btn btn-secondary" id="prev-page">
                                <i class="fas fa-chevron-left"></i> 上一页
                            </button>
                            <span id="page-info" class="pagination-info">第 1 页 / 共 0 页</span>
                            <button class="btn btn-secondary" id="next-page">
                                下一页 <i class="fas fa-chevron-right"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script type="text/javascript">
          // 全局定义Formatter对象
          // 确保Formatter是对象类型
          window.Formatter = (typeof window.Formatter === 'object' && window.Formatter !== null) ? window.Formatter : {};
          window.Formatter.formatCurrency = function(value) {
              return '¥' + value.toFixed(2);
          };
          // 移除未使用的模块导入
        // Ensure Formatter exists and has formatCurrency method
          document.addEventListener('DOMContentLoaded', function() {
              // Ensure Formatter exists and has formatCurrency method
              if (typeof window.Formatter !== 'object' || window.Formatter === null) {
                  window.Formatter = {};
              }
              window.Formatter.formatCurrency = function(value) {
                  return '¥' + value.toFixed(2);
              };

              // Initialize navigation
            initNavigation('main-menu', '薪酬管理', '薪酬概览');

            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                document.getElementById('username-display').textContent = username;
            }

            // 退出登录
            document.getElementById('logout-btn').addEventListener('click', function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });

            // 日期范围选择器切换
            const dateRangeSelect = document.getElementById('date-range');
            const customDateRange = document.getElementById('custom-date-range');

            dateRangeSelect.addEventListener('change', function() {
                if (this.value === 'custom') {
                    customDateRange.style.display = 'block';
                } else {
                    customDateRange.style.display = 'none';
                }
            });

            // 应用筛选
            document.getElementById('apply-filter').addEventListener('click', function() {
                loadSalaryData();
            });

            // 导出报表
            document.getElementById('export-report').addEventListener('click', function() {
                showToast('报表导出功能已触发，实际项目中会生成Excel/PDF文件', 'info');
            });

            // 分页按钮
            let currentPage = 1;
            const pageSize = 10;
            const prevPageBtn = document.getElementById('prev-page');
            const nextPageBtn = document.getElementById('next-page');
            const pageInfo = document.getElementById('page-info');

            prevPageBtn.addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    loadSalaryData();
                }
            });

            nextPageBtn.addEventListener('click', function() {
                // 总页数将在加载数据后更新
                const totalPagesText = pageInfo.textContent.match(/共 (\d+) 页/);
                const totalPages = totalPagesText ? parseInt(totalPagesText[1]) : 1;
                if (currentPage < totalPages) {
                    currentPage++;
                    loadSalaryData();
                }
            });

            // 初始化图表实例
            let departmentChart = null;
            let monthlyChart = null;

            // 初始化加载薪酬数据
            loadSalaryData();

            function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }

            function loadSalaryData() {
                // 显示加载状态
                showLoading(true);

                // 获取筛选条件
                const dateRange = dateRangeSelect.value;
                let startDate = '';
                let endDate = '';
                const department = document.getElementById('department-filter').value;

                if (dateRange === 'custom') {
                    startDate = document.getElementById('start-date').value;
                    endDate = document.getElementById('end-date').value;

                    // 验证日期
                    if (!startDate || !Validator.isDate(startDate)) {
                        showToast('请选择有效的开始日期', 'error');
                        showLoading(false);
                        return;
                    }
                    if (!endDate || !Validator.isDate(endDate)) {
                        showToast('请选择有效的结束日期', 'error');
                        showLoading(false);
                        return;
                    }
                    if (new Date(startDate) > new Date(endDate)) {
                        showToast('开始日期不能晚于结束日期', 'error');
                        showLoading(false);
                        return;
                    }
                }

                // 生成模拟薪酬数据
                const generateMockData = () => {
                    const departments = ['技术部', '市场部', '财务部', '人力资源部', '销售部'];
                    const positions = ['经理', '主管', '专员', '助理', '实习生'];
                    const employees = [];

                    // 生成15条模拟数据
                    for (let i = 1; i <= 15; i++) {
                        const baseSalary = Math.floor(Math.random() * 5000) + 5000; // 5000-10000
                        const bonus = Math.floor(Math.random() * 3000); // 0-3000
                        const benefits = Math.floor(Math.random() * 2000); // 0-2000

                        employees.push({
                            employeeId: i,
                            employeeName: `员工${i}`,
                            department: departments[Math.floor(Math.random() * departments.length)],
                            position: positions[Math.floor(Math.random() * positions.length)],
                            baseSalary: baseSalary,
                            bonus: bonus,
                            benefits: benefits,
                            total: baseSalary + bonus + benefits
                        });
                    }

                    return {
                        stats: {
                            totalSalary: employees.reduce((sum, emp) => sum + emp.total, 0),
                            avgSalary: employees.reduce((sum, emp) => sum + emp.total, 0) / employees.length,
                            salaryGrowth: (Math.random() * 10).toFixed(1),
                            benefitExpense: employees.reduce((sum, emp) => sum + emp.benefits, 0)
                        },
                        salaries: employees.slice((currentPage - 1) * pageSize, currentPage * pageSize),
                        totalCount: employees.length
                    };
                };

                // 使用模拟数据
                const data = generateMockData();
                showLoading(false);

                // 更新统计卡片
                updateStatsCards(data.stats);

                // 更新表格数据
                updateTableData(data.salaries);

                // 更新分页信息
                updatePagination(data.totalCount);
            }

            function updateStatsCards(stats) {
                if (stats) {
                    document.getElementById('total-salary').textContent = window.Formatter.formatCurrency(stats.totalSalary || 0);
                    document.getElementById('avg-salary').textContent = window.Formatter.formatCurrency(stats.avgSalary || 0);
                    document.getElementById('salary-growth').textContent = (stats.salaryGrowth || 0) + '%';
                    document.getElementById('benefit-expense').textContent = window.Formatter.formatCurrency(stats.benefitExpense || 0);
                }
            }

            function updateCharts(chartsData) {
                // 部门薪酬分布图表
                if (chartsData && chartsData.departmentDistribution) {
                    const deptCtx = document.getElementById('department-salary-chart').getContext('2d');

                    // 销毁旧图表
                    if (departmentChart) {
                        departmentChart.destroy();
                    }

                    departmentChart = new Chart(deptCtx, {
                        type: 'bar',
                        data: {
                            labels: chartsData.departmentDistribution.labels,
                            datasets: [{
                                label: '部门薪酬',
                                data: chartsData.departmentDistribution.values,
                                backgroundColor: [
                                    'rgba(75, 192, 192, 0.7)',
                                    'rgba(54, 162, 235, 0.7)',
                                    'rgba(255, 206, 86, 0.7)',
                                    'rgba(255, 99, 132, 0.7)',
                                    'rgba(153, 102, 255, 0.7)'
                                ],
                                borderColor: [
                                    'rgba(75, 192, 192, 1)',
                                    'rgba(54, 162, 235, 1)',
                                    'rgba(255, 206, 86, 1)',
                                    'rgba(255, 99, 132, 1)',
                                    'rgba(153, 102, 255, 1)'
                                ],
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '¥' + value.toLocaleString();
                                        }
                                    }
                                }
                            },
                            plugins: {
                                legend: {
                                    display: false
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            return '薪酬: ¥' + context.raw.toLocaleString();
                                        }
                                    }
                                }
                            },
                            animation: {
                                duration: 1000,
                                easing: 'easeOutQuart'
                            }
                        }
                    });
                }

                // 月度薪酬趋势图表
                if (chartsData && chartsData.monthlyTrend) {
                    const trendCtx = document.getElementById('monthly-salary-chart').getContext('2d');

                    // 销毁旧图表
                    if (monthlyChart) {
                        monthlyChart.destroy();
                    }

                    monthlyChart = new Chart(trendCtx, {
                        type: 'line',
                        data: {
                            labels: chartsData.monthlyTrend.labels,
                            datasets: [{
                                label: '月度薪酬',
                                data: chartsData.monthlyTrend.values,
                                fill: false,
                                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                                borderColor: 'rgba(255, 99, 132, 1)',
                                borderWidth: 2,
                                tension: 0.3,
                                pointBackgroundColor: 'rgba(255, 99, 132, 1)',
                                pointRadius: 4,
                                pointHoverRadius: 6
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '¥' + value.toLocaleString();
                                        }
                                    }
                                }
                            },
                            plugins: {
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            return '薪酬: ¥' + context.raw.toLocaleString();
                                        }
                                    }
                                }
                            },
                            animation: {
                                duration: 1000,
                                easing: 'easeOutQuart'
                            }
                        }
                    });
                }
            }

            function updateTableData(salaries) {
                const tableBody = document.getElementById('salary-table-body');
                tableBody.innerHTML = '';

                if (salaries && salaries.length > 0) {
                    salaries.forEach(salary => {
                        const total = (salary.baseSalary || 0) + (salary.bonus || 0) + (salary.benefits || 0);
                        const row = document.createElement('tr');

                        // 添加行悬停效果
                        row.classList.add('hover-row');

                        row.innerHTML = `
                            <td>${salary.employeeName}</td>
                            <td>${salary.department}</td>
                            <td>${salary.position}</td>
                            <td>¥${window.Formatter.formatCurrency(salary.baseSalary || 0)}</td>
                            <td>¥${window.Formatter.formatCurrency(salary.bonus || 0)}</td>
                            <td>¥${window.Formatter.formatCurrency(salary.benefits || 0)}</td>
                            <td>¥${window.Formatter.formatCurrency(total)}</td>
                            <td><a href="manage.html?id=${salary.employeeId}" class="btn btn-sm btn-primary">
                                <i class="fas fa-edit"></i> 管理
                            </a></td>
                        `;

                        tableBody.appendChild(row);
                    });
                } else {
                    const emptyRow = document.createElement('tr');
                    emptyRow.innerHTML = '<td colspan="8" class="no-data text-center">暂无数据</td>';
                    tableBody.appendChild(emptyRow);
                }
            }

            function updatePagination(totalCount) {
                const totalPages = Math.ceil(totalCount / pageSize) || 1;
                pageInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;

                // 禁用/启用分页按钮
                prevPageBtn.disabled = currentPage === 1;
                nextPageBtn.disabled = currentPage >= totalPages;

                // 更新按钮样式
                if (currentPage === 1) {
                    prevPageBtn.classList.add('disabled');
                } else {
                    prevPageBtn.classList.remove('disabled');
                }

                if (currentPage >= totalPages) {
                    nextPageBtn.classList.add('disabled');
                } else {
                    nextPageBtn.classList.remove('disabled');
                }
            }

            function showToast(message, type) {
                const toast = document.getElementById('toast');
                toast.textContent = message;
                toast.className = 'toast show ' + type;

                setTimeout(() => {
                    toast.className = 'toast';
                }, 3000);
            }

            function showLoading(show) {
                const loadingOverlay = document.getElementById('loading-overlay');
                loadingOverlay.style.display = show ? 'flex' : 'none';
            }
        });
    </script>
</body>
</html>